package net.thxjj.adminServer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceStatusClient;
import com.ctg.ag.sdk.biz.aep_device_status.GetDeviceStatusHisInPageRequest;
import com.ctg.ag.sdk.biz.aep_device_status.GetDeviceStatusHisInPageResponse;
import net.thxjj.adminServer.dao.DeviceDao;
import net.thxjj.adminServer.entity.Const;
import net.thxjj.adminServer.entity.LoginHadleEvent;
import net.thxjj.adminServer.entity.StaticBean;
import net.thxjj.adminServer.entity.aep.*;
import net.thxjj.adminServer.mongodao.MongoLoginDao;
import net.thxjj.adminServer.mongodao.MongoLoginHandleDao;
import net.thxjj.adminServer.mongodao.MongoProfileDao;
import net.thxjj.adminServer.service.IProfileLogService;
import net.thxjj.adminServer.util.ParameterMap;
import net.thxjj.sitermodel.Device;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class ProfileLogService implements IProfileLogService {

    @Autowired
    private MongoLoginDao mongoLoginDao;

    @Autowired
    private MongoProfileDao mongoProfileDao;

    @Autowired
    private MongoLoginHandleDao mongoLoginHandleDao;

    @Autowired
    private DeviceDao deviceDao;

    @Async("asyncExecutor")
    @Override
    public void mqAddDevLog(ProfileLog profileLog) {
        mongoProfileDao.saveProfileLog(profileLog);
    }

    @Async("asyncExecutor")
    @Override
    public void mqAddLoginData(LoginData loginData) {
        mongoLoginDao.saveLoginData(loginData);
    }



    @Async("asyncExecutor")
    @Override
    public void updateDeviceData(Device device) {
        Calendar now = Calendar.getInstance();
        long curtime = now.getTime().getTime();
        now.add(Calendar.DAY_OF_MONTH, -30);
        long histime = now.getTime().getTime()+10000;
        if(histime<device.getCreateTime()){
            histime = device.getCreateTime();
        }
        AepDeviceStatusClient client = AepDeviceStatusClient.newClient()
                .appKey(Const.APPKEY).appSecret(Const.APPSECRET)
                .build();
        JSONObject param = new JSONObject();
        param.put("productId",Const.PROFILE_PRODUCT_ID);
        param.put("deviceId",device.getDeviceId());
        param.put("begin_timestamp",histime);
        param.put("end_timestamp",curtime);
        param.put("page_size",100);
        boolean flag = true;
        String page_timestamp = "";

        do {
            try {
                GetDeviceStatusHisInPageRequest request = new GetDeviceStatusHisInPageRequest();
                param.put("page_timestamp",page_timestamp);
                request.setBody(param.toJSONString().getBytes());	//具体格式见前面请求body说明
                GetDeviceStatusHisInPageResponse statusHisInPageResponse = client.getDeviceStatusHisInPage(request);
                String body = new String(statusHisInPageResponse.getBody());
                JSONObject jsonObject = JSON.parseObject(body);
                int code = jsonObject.getIntValue("code");
                page_timestamp = jsonObject.getString("page_timestamp");
                JSONArray array = jsonObject.getJSONArray("deviceStatusList");
                if(code==0){
                    if(StringUtils.isEmpty(page_timestamp)){
                        flag = false;
                    }
                if(array.size()>0){
                    List<ProfileLog> profileLogList = new ArrayList<>();
                    List<LoginData> profileLoginDataList = new ArrayList<>();
                    for(int i=0;i<array.size();i++){
                            JSONObject a = array.getJSONObject(i);
                            String resulet = a.getString("serviceData");
                            long timestamp = a.getLongValue("timestamp");
                            if(resulet.contains("TAU")){
                                ProfileLoginData profileLoginData = JSONObject.parseObject(resulet,ProfileLoginData.class);
                                profileLoginData.setDeviceId(device.getDeviceId());
                                profileLoginData.setTimestamp(timestamp);
                                LoginData loginData = new LoginData().setActive_time(profileLoginData.getActiveTime())
                                        .setActive_time_flag(profileLoginData.getActiveTimeFlag())
                                        .setDevice_type(profileLoginData.getDevice_Type())
                                        .setDeviceId(profileLoginData.getDeviceId())
                                        .setHardware_version(profileLoginData.getHardwareVersion())
                                        .setIMEI(profileLoginData.getIMEI())
                                        .setIMSI(profileLoginData.getIMSI())
                                        .setManufacturer_name(profileLoginData.getManufacturer())
                                        .setSoftware_version(profileLoginData.getFirmwareVersion())
                                        .setTau(profileLoginData.getTAU())
                                        .setTau_flag(profileLoginData.getTAU_Flag())
                                        .setTimestamp(profileLoginData.getTimestamp());
                                profileLoginDataList.add(loginData);
                            }else if(resulet.contains("TData")){
                                ProfileLog profileLog = JSONObject.parseObject(resulet,ProfileLog.class);
                                profileLog.setDeviceId(device.getDeviceId());
                                profileLog.setTimestamp(timestamp);
                                profileLogList.add(profileLog);
                            }
                    }

                    try {
                        if(profileLogList.size()>0){
                            mongoProfileDao.saveProfileDatas(profileLogList);
                        }

                        if(profileLoginDataList.size()>0)
                            mongoLoginDao.saveLoginDatas(profileLoginDataList);
                    }catch (Exception e){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        e.printStackTrace();
                    }

                }else{
                    flag = false;
                }
            }else {
                flag = false;
            }



            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }
        }
        while (flag);
        client.shutdown();
    }

    @Override
    public ProfileLog ShadowStatus(String device_id) {
        return mongoProfileDao.getSmokeStatus(device_id);
    }


    @Override
    public LoginData ShadowLoginStatus(String device_id) {
        return mongoLoginDao.getNewestLoginInfo(device_id);
    }

    @Override
    public ParameterMap HeartBeat(String device_id) {
        List<ProfileLog> profileLogList = mongoProfileDao.getAlllogs(device_id);
        long heartbeart = profileLogList.size();
        if(heartbeart<=0){
            ParameterMap map = new ParameterMap();
            map.put("datasetId","heartbeat");
            map.put("value",0);
            return map;
        }

        long set_heart_time;
        Device device = deviceDao.getDeviceInfo(device_id);
        if(device.getHeartTime()<=0){
            set_heart_time = 1200;
        }else {
            set_heart_time = device.getHeartTime();
        }
        long heartbeart_lilun = 0;
        long heartlv = 0;
        ProfileLog data = profileLogList.get(0);
        if(data!=null){
            long timelong = data.getTimestamp();
            long cur_timelong = System.currentTimeMillis();
            if(cur_timelong>timelong){
                long a  = cur_timelong - timelong;
                heartbeart_lilun = (a/(set_heart_time*60000))+1;
            }
        }
        if(heartbeart>heartbeart_lilun){
            heartlv =100;
        }else{
            heartlv = heartbeart * 100 / heartbeart_lilun;
        }
        ParameterMap map = new ParameterMap();
        map.put("datasetId","heartbeat");
        map.put("value",heartlv);
        return map;
    }

    @Override
    public List<List<Object>> getLoginErrList(String device_id) {
        List<LoginHadleEvent> list =  mongoLoginDao.getLoginHandleWithLog(device_id);
        List<List<Object>> listLogin = new ArrayList<>();
        for (LoginHadleEvent map:list) {
            long ad = map.getUserId();
            long value = 1;
                if(ad>0){
                    value = 2;
                }
            long timestamp = map.getTimestamp();
            List<Object> lista = new ArrayList<>();
            lista.add(timestamp);
            lista.add(value);
            listLogin.add(lista);
        }
        return listLogin;
    }


    @Override
    public ParameterMap isMultiLoginError(String device_id) {
        List<LoginHadleEvent> loginHandleInfo = mongoLoginHandleDao.getAllLoginHandleInfo(device_id);
        long timestamp = 0;
        long value = 0;
        if(loginHandleInfo==null || loginHandleInfo.size()==0){
            List<LoginData> list = mongoLoginDao.getLoginInfoByTime(device_id,0);
            if(list.size()>1){
                value = 1;
                timestamp = list.get(list.size()-1).getTimestamp();
            }
        }else{
            long a = loginHandleInfo.get(loginHandleInfo.size()-1).getTimestamp();
            List<LoginData> list = mongoLoginDao.getLoginInfoByTime(device_id,a);
            if(list.size()>0){
                value = 1;
                timestamp = list.get(list.size()-1).getTimestamp();
            }
        }

        ParameterMap map = new ParameterMap();
        map.put("datasetId","multlogin");
        map.put("value",value);
        map.put("timestamp",timestamp);
        return map;
    }

    @Override
    public List<ProfileLog> getSmokeStatusList(String device_id, long start_time, long end_time) {
        return mongoProfileDao.getProfileLogsByTime(device_id,start_time,end_time);
    }

    @Override
    public StaticBean getSmokeValueStatic(String device_id, long start_time, long end_time) {
        return mongoProfileDao.getSmokeValueStatic(device_id,start_time,end_time);
    }

    @Override
    public StaticBean getBatteryValueStatic(String device_id, long start_time, long end_time) {
        return mongoProfileDao.getBatteryValueStatic(device_id,start_time,end_time);
    }

    @Override
    public StaticBean getSnrStatic(String device_id, long start_time, long end_time) {
        return mongoProfileDao.getSnrStatic(device_id,start_time,end_time);
    }

    @Override
    public StaticBean getRsrpStatic(String device_id, long start_time, long end_time) {
        return mongoProfileDao.getRsrpStatic(device_id,start_time,end_time);
    }

    @Override
    public StaticBean getTempStatic(String device_id, long start_time, long end_time) {
        return mongoProfileDao.getTempStatic(device_id,start_time,end_time);
    }

    @Override
    public StaticBean getCsqStatic(String device_id, long start_time, long end_time) {
        return mongoProfileDao.getCsqStatic(device_id,start_time,end_time);
    }
}
